<template>
  <view class="trust-sync-manager">
    <!-- 同步状态显示 -->
    <view class="sync-status" :class="syncStatusClass">
      <view class="status-indicator">
        <text class="status-icon">{{ syncStatusIcon }}</text>
        <text class="status-text">{{ syncStatusText }}</text>
      </view>
      
      <view class="sync-info" v-if="showSyncInfo">
        <text class="last-sync">最后同步: {{ formatTime(lastSyncTime) }}</text>
        <text class="sync-count">同步次数: {{ syncCount }}</text>
      </view>
    </view>
    
    <!-- 同步控制面板 -->
    <view class="sync-controls" v-if="showControls">
      <button 
        class="sync-btn" 
        :class="{ 'syncing': isSyncing }"
        @click="manualSync"
        :disabled="isSyncing"
      >
        <text class="btn-icon">{{ isSyncing ? '🔄' : '🔄' }}</text>
        <text class="btn-text">{{ isSyncing ? '同步中...' : '立即同步' }}</text>
      </button>
      
      <button class="sync-btn secondary" @click="showSyncSettings">
        <text class="btn-icon">⚙️</text>
        <text class="btn-text">设置</text>
      </button>
    </view>
    
    <!-- 同步冲突解决 -->
    <view class="sync-conflicts" v-if="conflicts.length > 0">
      <text class="conflicts-title">同步冲突</text>
      <view class="conflicts-list">
        <view 
          class="conflict-item" 
          v-for="conflict in conflicts" 
          :key="conflict.id"
        >
          <view class="conflict-header">
            <text class="conflict-type">{{ conflict.type }}</text>
            <text class="conflict-time">{{ formatTime(conflict.timestamp) }}</text>
          </view>
          <text class="conflict-description">{{ conflict.description }}</text>
          <view class="conflict-actions">
            <button class="action-btn primary" @click="resolveConflict(conflict, 'local')">
              <text class="btn-text">使用本地</text>
            </button>
            <button class="action-btn secondary" @click="resolveConflict(conflict, 'remote')">
              <text class="btn-text">使用远程</text>
            </button>
            <button class="action-btn tertiary" @click="resolveConflict(conflict, 'merge')">
              <text class="btn-text">合并</text>
            </button>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 同步历史 -->
    <view class="sync-history" v-if="showHistory">
      <text class="history-title">同步历史</text>
      <view class="history-list">
        <view 
          class="history-item" 
          v-for="entry in syncHistory" 
          :key="entry.id"
          :class="entry.status"
        >
          <view class="history-header">
            <text class="history-icon">{{ getHistoryIcon(entry.status) }}</text>
            <text class="history-time">{{ formatTime(entry.timestamp) }}</text>
          </view>
          <text class="history-description">{{ entry.description }}</text>
          <text class="history-details" v-if="entry.details">{{ entry.details }}</text>
        </view>
      </view>
    </view>
    
    <!-- 同步设置模态框 -->
    <view v-if="showSettingsModal" class="settings-modal">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">同步设置</text>
          <button class="close-btn" @click="closeSettings">×</button>
        </view>
        
        <view class="settings-content">
          <view class="setting-item">
            <text class="setting-label">自动同步</text>
            <switch 
              :checked="autoSync" 
              @change="toggleAutoSync"
              color="#667eea"
            />
          </view>
          
          <view class="setting-item">
            <text class="setting-label">同步间隔</text>
            <picker 
              :value="syncIntervalIndex" 
              :range="syncIntervals" 
              @change="changeSyncInterval"
            >
              <text class="picker-text">{{ syncIntervals[syncIntervalIndex] }}</text>
            </picker>
          </view>
          
          <view class="setting-item">
            <text class="setting-label">冲突解决策略</text>
            <picker 
              :value="conflictStrategyIndex" 
              :range="conflictStrategies" 
              @change="changeConflictStrategy"
            >
              <text class="picker-text">{{ conflictStrategies[conflictStrategyIndex] }}</text>
            </picker>
          </view>
          
          <view class="setting-item">
            <text class="setting-label">数据加密</text>
            <switch 
              :checked="dataEncryption" 
              @change="toggleDataEncryption"
              color="#667eea"
            />
          </view>
        </view>
        
        <view class="modal-actions">
          <button class="action-btn secondary" @click="closeSettings">
            <text class="btn-text">取消</text>
          </button>
          <button class="action-btn primary" @click="saveSettings">
            <text class="btn-text">保存</text>
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import trustSyncManager from '@/utils/trust-sync-manager.js'

export default {
  name: 'TrustSyncManager',
  props: {
    showControls: {
      type: Boolean,
      default: true
    },
    showSyncInfo: {
      type: Boolean,
      default: true
    },
    showHistory: {
      type: Boolean,
      default: false
    },
    autoSync: {
      type: Boolean,
      default: true
    }
  },
  
  data() {
    return {
      syncStatus: 'disconnected', // disconnected, connecting, connected, syncing, error
      lastSyncTime: null,
      syncCount: 0,
      isSyncing: false,
      conflicts: [],
      syncHistory: [],
      showSettingsModal: false,
      syncIntervalIndex: 1, // 默认5分钟
      conflictStrategyIndex: 0, // 默认询问用户
      dataEncryption: true,
      syncIntervals: ['1分钟', '5分钟', '15分钟', '30分钟', '1小时'],
      conflictStrategies: ['询问用户', '使用本地', '使用远程', '自动合并']
    }
  },
  
  computed: {
    syncStatusClass() {
      return `status-${this.syncStatus}`
    },
    
    syncStatusIcon() {
      const icons = {
        disconnected: '🔴',
        connecting: '🟡',
        connected: '🟢',
        syncing: '🔄',
        error: '❌'
      }
      return icons[this.syncStatus] || '❓'
    },
    
    syncStatusText() {
      const texts = {
        disconnected: '未连接',
        connecting: '连接中...',
        connected: '已连接',
        syncing: '同步中...',
        error: '同步错误'
      }
      return texts[this.syncStatus] || '未知状态'
    }
  },
  
  onLoad() {
    this.initializeSync()
  },
  
  methods: {
    // 初始化同步
    async initializeSync() {
      try {
        this.syncStatus = 'connecting'
        
        // 加载同步设置
        await this.loadSyncSettings()
        
        // 加载同步历史
        this.syncHistory = trustSyncManager.getSyncHistory()
        this.syncCount = this.syncHistory.length
        
        // 检查连接状态
        const isConnected = await trustSyncManager.checkConnection()
        this.syncStatus = isConnected ? 'connected' : 'disconnected'
        
        // 检查冲突
        this.conflicts = trustSyncManager.getConflicts()
        
        // 开始自动同步
        if (this.autoSync) {
          this.startAutoSync()
        }
        
      } catch (error) {
        console.error('Failed to initialize sync:', error)
        this.syncStatus = 'error'
      }
    },
    
    // 加载同步设置
    async loadSyncSettings() {
      try {
        const settings = await trustSyncManager.getSyncSettings()
        this.autoSync = settings.autoSync
        this.syncIntervalIndex = settings.syncIntervalIndex
        this.conflictStrategyIndex = settings.conflictStrategyIndex
        this.dataEncryption = settings.dataEncryption
      } catch (error) {
        console.error('Failed to load sync settings:', error)
      }
    },
    
    // 手动同步
    async manualSync() {
      if (this.isSyncing) return
      
      try {
        this.isSyncing = true
        this.syncStatus = 'syncing'
        
        const result = await trustSyncManager.syncData()
        
        if (result.success) {
          this.syncStatus = 'connected'
          this.lastSyncTime = Date.now()
          this.syncCount++
          
          // 添加同步历史
          this.syncHistory.unshift({
            id: Date.now(),
            status: 'success',
            description: '手动同步成功',
            timestamp: Date.now()
          })
          
          // 限制历史记录数量
          if (this.syncHistory.length > 50) {
            this.syncHistory = this.syncHistory.slice(0, 50)
          }
          
          uni.showToast({
            title: '同步成功',
            icon: 'success'
          })
        } else {
          this.syncStatus = 'error'
          this.syncHistory.unshift({
            id: Date.now(),
            status: 'error',
            description: result.error || '同步失败',
            timestamp: Date.now()
          })
          
          uni.showToast({
            title: '同步失败',
            icon: 'error'
          })
        }
        
      } catch (error) {
        console.error('Manual sync failed:', error)
        this.syncStatus = 'error'
        uni.showToast({
          title: '同步失败',
          icon: 'error'
        })
      } finally {
        this.isSyncing = false
      }
    },
    
    // 开始自动同步
    startAutoSync() {
      if (this.autoSyncInterval) {
        clearInterval(this.autoSyncInterval)
      }
      
      const interval = this.getSyncInterval()
      this.autoSyncInterval = setInterval(() => {
        this.manualSync()
      }, interval)
    },
    
    // 停止自动同步
    stopAutoSync() {
      if (this.autoSyncInterval) {
        clearInterval(this.autoSyncInterval)
        this.autoSyncInterval = null
      }
    },
    
    // 获取同步间隔
    getSyncInterval() {
      const intervals = [60000, 300000, 900000, 1800000, 3600000] // 1分钟到1小时
      return intervals[this.syncIntervalIndex] || 300000
    },
    
    // 显示同步设置
    showSyncSettings() {
      this.showSettingsModal = true
    },
    
    // 关闭同步设置
    closeSettings() {
      this.showSettingsModal = false
    },
    
    // 切换自动同步
    toggleAutoSync(event) {
      this.autoSync = event.detail.value
      
      if (this.autoSync) {
        this.startAutoSync()
      } else {
        this.stopAutoSync()
      }
    },
    
    // 更改同步间隔
    changeSyncInterval(event) {
      this.syncIntervalIndex = event.detail.value
      
      if (this.autoSync) {
        this.startAutoSync()
      }
    },
    
    // 更改冲突策略
    changeConflictStrategy(event) {
      this.conflictStrategyIndex = event.detail.value
    },
    
    // 切换数据加密
    toggleDataEncryption(event) {
      this.dataEncryption = event.detail.value
    },
    
    // 保存设置
    async saveSettings() {
      try {
        const settings = {
          autoSync: this.autoSync,
          syncIntervalIndex: this.syncIntervalIndex,
          conflictStrategyIndex: this.conflictStrategyIndex,
          dataEncryption: this.dataEncryption
        }
        
        await trustSyncManager.saveSyncSettings(settings)
        
        if (this.autoSync) {
          this.startAutoSync()
        } else {
          this.stopAutoSync()
        }
        
        this.closeSettings()
        
        uni.showToast({
          title: '设置已保存',
          icon: 'success'
        })
        
      } catch (error) {
        console.error('Failed to save settings:', error)
        uni.showToast({
          title: '保存失败',
          icon: 'error'
        })
      }
    },
    
    // 解决冲突
    async resolveConflict(conflict, resolution) {
      try {
        const result = await trustSyncManager.resolveConflict(conflict.id, resolution)
        
        if (result.success) {
          // 从冲突列表中移除
          this.conflicts = this.conflicts.filter(c => c.id !== conflict.id)
          
          // 添加解决历史
          this.syncHistory.unshift({
            id: Date.now(),
            status: 'resolved',
            description: `冲突已解决: ${resolution}`,
            timestamp: Date.now()
          })
          
          uni.showToast({
            title: '冲突已解决',
            icon: 'success'
          })
        } else {
          uni.showToast({
            title: '解决失败',
            icon: 'error'
          })
        }
        
      } catch (error) {
        console.error('Failed to resolve conflict:', error)
        uni.showToast({
          title: '解决失败',
          icon: 'error'
        })
      }
    },
    
    // 获取历史图标
    getHistoryIcon(status) {
      const icons = {
        success: '✅',
        error: '❌',
        resolved: '🔧',
        info: 'ℹ️'
      }
      return icons[status] || '❓'
    },
    
    // 格式化时间
    formatTime(timestamp) {
      if (!timestamp) return '从未'
      
      const date = new Date(timestamp)
      const now = new Date()
      const diff = now - date
      
      if (diff < 60000) {
        return '刚刚'
      } else if (diff < 3600000) {
        return `${Math.floor(diff / 60000)}分钟前`
      } else if (diff < 86400000) {
        return `${Math.floor(diff / 3600000)}小时前`
      } else {
        return date.toLocaleString()
      }
    }
  },
  
  beforeDestroy() {
    this.stopAutoSync()
  }
}
</script>

<style scoped>
.trust-sync-manager {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

/* 同步状态 */
.sync-status {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
  padding: 12rpx 16rpx;
  border-radius: 12rpx;
  transition: all 0.3s ease;
}

.sync-status.status-disconnected {
  background: rgba(244, 67, 54, 0.1);
  border: 1rpx solid #f44336;
}

.sync-status.status-connecting {
  background: rgba(255, 152, 0, 0.1);
  border: 1rpx solid #ff9800;
}

.sync-status.status-connected {
  background: rgba(76, 175, 80, 0.1);
  border: 1rpx solid #4caf50;
}

.sync-status.status-syncing {
  background: rgba(33, 150, 243, 0.1);
  border: 1rpx solid #2196f3;
}

.sync-status.status-error {
  background: rgba(244, 67, 54, 0.1);
  border: 1rpx solid #f44336;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.status-icon {
  font-size: 20rpx;
}

.status-text {
  font-size: 18rpx;
  font-weight: bold;
  color: #333;
}

.sync-info {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4rpx;
}

.last-sync,
.sync-count {
  font-size: 14rpx;
  color: #666;
}

/* 同步控制 */
.sync-controls {
  display: flex;
  gap: 12rpx;
  margin-bottom: 16rpx;
}

.sync-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  padding: 12rpx 16rpx;
  border: none;
  border-radius: 12rpx;
  font-size: 18rpx;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
}

.sync-btn:not(.secondary) {
  background: #667eea;
  color: white;
}

.sync-btn:not(.secondary):hover {
  background: #5a6fd8;
  transform: translateY(-2rpx);
}

.sync-btn.secondary {
  background: #f5f5f5;
  color: #666;
}

.sync-btn.secondary:hover {
  background: #e0e0e0;
  transform: translateY(-2rpx);
}

.sync-btn.syncing {
  background: #ccc;
  cursor: not-allowed;
  transform: none;
}

.sync-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-icon {
  font-size: 16rpx;
}

.btn-text {
  font-size: 16rpx;
}

/* 同步冲突 */
.sync-conflicts {
  margin-bottom: 16rpx;
}

.conflicts-title {
  font-size: 20rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 12rpx;
}

.conflicts-list {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.conflict-item {
  background: rgba(255, 152, 0, 0.1);
  border: 1rpx solid #ff9800;
  border-radius: 12rpx;
  padding: 16rpx;
}

.conflict-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8rpx;
}

.conflict-type {
  font-size: 18rpx;
  font-weight: bold;
  color: #333;
}

.conflict-time {
  font-size: 14rpx;
  color: #666;
}

.conflict-description {
  font-size: 16rpx;
  color: #666;
  margin-bottom: 12rpx;
  display: block;
}

.conflict-actions {
  display: flex;
  gap: 8rpx;
}

.action-btn {
  flex: 1;
  padding: 8rpx 12rpx;
  border: none;
  border-radius: 8rpx;
  font-size: 16rpx;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
}

.action-btn.primary {
  background: #4caf50;
  color: white;
}

.action-btn.primary:hover {
  background: #45a049;
}

.action-btn.secondary {
  background: #2196f3;
  color: white;
}

.action-btn.secondary:hover {
  background: #1976d2;
}

.action-btn.tertiary {
  background: #ff9800;
  color: white;
}

.action-btn.tertiary:hover {
  background: #f57c00;
}

/* 同步历史 */
.sync-history {
  margin-bottom: 16rpx;
}

.history-title {
  font-size: 20rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 12rpx;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
  max-height: 300rpx;
  overflow-y: auto;
}

.history-item {
  padding: 12rpx;
  border-radius: 8rpx;
  border-left: 4rpx solid #e0e0e0;
}

.history-item.success {
  background: rgba(76, 175, 80, 0.1);
  border-left-color: #4caf50;
}

.history-item.error {
  background: rgba(244, 67, 54, 0.1);
  border-left-color: #f44336;
}

.history-item.resolved {
  background: rgba(255, 152, 0, 0.1);
  border-left-color: #ff9800;
}

.history-item.info {
  background: rgba(33, 150, 243, 0.1);
  border-left-color: #2196f3;
}

.history-header {
  display: flex;
  align-items: center;
  gap: 8rpx;
  margin-bottom: 4rpx;
}

.history-icon {
  font-size: 16rpx;
}

.history-time {
  font-size: 14rpx;
  color: #666;
}

.history-description {
  font-size: 16rpx;
  color: #333;
  display: block;
  margin-bottom: 4rpx;
}

.history-details {
  font-size: 14rpx;
  color: #666;
}

/* 设置模态框 */
.settings-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 20rpx;
  padding: 30rpx;
  max-width: 500rpx;
  max-height: 80vh;
  overflow-y: auto;
  color: #333;
  margin: 20rpx;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
  border-bottom: 1rpx solid #e0e0e0;
  padding-bottom: 16rpx;
}

.modal-title {
  font-size: 24rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  width: 32rpx;
  height: 32rpx;
  border-radius: 50%;
  background: #f5f5f5;
  color: #666;
  font-size: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.settings-content {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  margin-bottom: 24rpx;
}

.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.setting-label {
  font-size: 18rpx;
  color: #333;
  flex: 1;
}

.picker-text {
  font-size: 16rpx;
  color: #667eea;
  padding: 8rpx 12rpx;
  background: #f5f5f5;
  border-radius: 8rpx;
}

.modal-actions {
  display: flex;
  gap: 12rpx;
}

.modal-actions .action-btn {
  flex: 1;
  padding: 12rpx 20rpx;
  border: none;
  border-radius: 12rpx;
  font-size: 18rpx;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
}

.modal-actions .action-btn.primary {
  background: #667eea;
  color: white;
}

.modal-actions .action-btn.primary:hover {
  background: #5a6fd8;
}

.modal-actions .action-btn.secondary {
  background: #f5f5f5;
  color: #666;
}

.modal-actions .action-btn.secondary:hover {
  background: #e0e0e0;
}

/* 响应式设计 */
@media (max-width: 768rpx) {
  .trust-sync-manager {
    padding: 16rpx;
  }
  
  .sync-controls {
    flex-direction: column;
  }
  
  .conflict-actions {
    flex-direction: column;
  }
  
  .modal-content {
    margin: 16rpx;
    max-width: calc(100% - 32rpx);
  }
}
</style>

